 package com.hanvon.faceRec;

 import android.graphics.*;
 import android.hardware.Camera;
 import android.util.Log;

 import java.io.*;
 import java.util.Calendar;
 import java.util.Date;

 public class UtilFunc {
     /*
      * 将Param参数格式存储
      * */
     public static void saveOutParamData(byte[] data,int width,int height,FacePos facepos) throws IOException {
         FileOutputStream outStream = null;
         File file = new File("/mnt/sdcard/Camera");
         if(!file.exists()){
             file.mkdir();
         }

         try {
                 YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, width, height, null);

                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
                 yuvimage.compressToJpeg(new Rect(0, 0,width, height), 80, baos);

                 Bitmap bmp = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);

                 long time  = System.currentTimeMillis();

                 Log.d("222222222222", ""+baos.toByteArray().length+" * ");
                 outStream = new FileOutputStream(String.format("/mnt/sdcard/Camera/%d_%s_%s.jpg",time, String.valueOf(width), String.valueOf(height)));
                 bmp.compress(Bitmap.CompressFormat.JPEG, 85, outStream);
                 outStream.write(baos.toByteArray());
                 outStream.close();

                 String strName = String.format("/mnt/sdcard/Camera/%d_%s_%s.txt",
                         time, String.valueOf(width), String.valueOf(height));

                 String strText = String.format("nCol:%d,nRow:%d,nWidth:%d,nHeight:%d,leftx:%d,lefty:%d,rightx:%d,righty:%d",
                         facepos.nCol,facepos.nRow,facepos.nWidth,facepos.nHeight,facepos.leftx,facepos.lefty,facepos.rightx,facepos.righty);

                 outStream = new FileOutputStream(strName);
                 OutputStreamWriter writer = new OutputStreamWriter(outStream);
                 writer.write(strText);
                 writer.close();
                 outStream.close();


         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
         }
     }

     /*
      * 将YUV格式存储成图片
      * */
     public static void saveYUVtoPicture(byte[] data,int width,int height) throws IOException {
         FileOutputStream outStream = null;
         File file = new File("/mnt/sdcard/Camera");
         if(!file.exists()){
             file.mkdir();
         }

         try {

                 YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, width, height, null);


                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
                 yuvimage.compressToJpeg(new Rect(0, 0,width, height), 80, baos);

                 Bitmap bmp = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);


             Log.d("222222222222", ""+baos.toByteArray().length+" * ");
             outStream = new FileOutputStream(
                     String.format("/mnt/sdcard/Camera/%d_%s_%s.jpg",
                             System.currentTimeMillis(), String.valueOf(width), String.valueOf(height)));
             bmp.compress(Bitmap.CompressFormat.JPEG, 85, outStream);
             outStream.write(baos.toByteArray());
             outStream.close();

         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
         }
     }

     /*
      * 在识别成功后将YUV格式存储成图片
      * */
     public static void saveYUVtoPictureCamera(byte[] data,int nWidth,int nHeigth,int lefteyex,int lefteyey,int righteyex,int righteyey ,int userID) throws IOException {
         String strResult = "";
         StringBuilder builder = new StringBuilder("/mnt/sdcard/RecCaptureImg");
         builder.append("/");
         builder.append(String.valueOf(userID));
         builder.append("/");
         Calendar calendar = Calendar.getInstance();
         Date trialTime = new Date();
         calendar.setTime(trialTime);
         builder.append(String.format("%04d_%02d_%02d",calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)));

         FileOutputStream outStream = null;
         //检查是否已经创建，如果未创建则创建
         File file = new File(builder.toString());
         if( !file.exists())
         {
             file.mkdirs();
         }

         builder.append("/");

         try {
             //int rgbdata[]= new int[width*height];
                 YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, nWidth, nHeigth, null);

                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
                 yuvimage.compressToJpeg(new Rect(0, 0,nWidth, nHeigth), 80, baos);

                 Bitmap bmp = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.toByteArray().length);


 //				bmp.getPixels(rgbdata, 0, width, 0, 0, width, height);
             Log.d("222222222222", ""+baos.toByteArray().length+" * ");
             outStream = new FileOutputStream(
                     String.format("%s%d_lx%s_ly%s_rx%s_ry%s.jpg",builder.toString(), System.currentTimeMillis(), String.valueOf(lefteyex), String.valueOf(lefteyey), String.valueOf(righteyex), String.valueOf(righteyey)));
             bmp.compress(Bitmap.CompressFormat.JPEG, 85, outStream);
             outStream.write(baos.toByteArray());
             outStream.close();

         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         } finally {
         }
     }

      public static void rotateYUV240SP_Clockwise(byte[] src,byte[] des,int width,int height)
      {
             int wh = width * height;
             //旋转Y
             int k = 0;
             for(int i=0;i<width;i++) {
                 for(int j=0;j<height;j++)
                 {
                       des[k] = src[width*(height-j-1) + i];
                       k++;
                 }
             }

             for(int i=0;i<width;i+=2) {
                 for(int j=0;j<height/2;j++)
                 {
                       des[k] = src[wh+ width*(height/2-j-1) + i];
                       des[k+1]=src[wh + width*(height/2-j-1) + i+1];
                       k+=2;
                 }
             }

      }
      public static void rotateYUV240SP_AntiClockwise(byte[] src,byte[] des,int width,int height)
      {
             int wh = width * height;
             //旋转Y
             int k = 0;
             for(int i=0;i<width;i++) {
                 for(int j=0;j<height;j++)
                 {
                       des[k] = src[width*j + width-i-1];
                       k++;
                 }
             }

             for(int i=0;i<width;i+=2) {
                 for(int j=0;j<height/2;j++)
                 {
                       des[k+1] = src[wh+ width*j + width-i-1];
                       des[k]=src[wh + width*j + width-(i+1)-1];
                       k+=2;
                 }
             }

     }

      public static void rotateYUV240SP_FlipY180(byte[] src,byte[] des,int width,int height)
      {
             int wh = width * height;
             //旋转Y
             int k = 0;
            for(int i=0;i<height;i++) {
                 for(int j=0;j<width;j++)
                 {
                       des[k] = src[width*(height-i-1) + j];
                       k++;
                 }
             }
             for(int i=0;i<height/2;i++) {
                 for(int j=0;j<width;j+=2)
                 {
                       des[k]= src[wh + width*(height/2 -i-1) + j];
                       des[k+1] = src[wh+ width*(height/2 -i-1) + j+1];
                       k+=2;
                 }
             }

     }
      //it works becuase in YCbCr_420_SP and YCbCr_422_SP, the Y channel is planar and appears first
     public static void rotateYuvData(byte[] rotatedData, byte[] data, int width, int height,int nCase)
     {
         if( nCase == 0)
         {
             rotateYUV240SP_Clockwise(data,rotatedData,width,height);
         }
         else if(nCase == 2)
         {
             rotateYUV240SP_FlipY180(data,rotatedData,width,height);
         }
         else
         {
             rotateYUV240SP_AntiClockwise(data,rotatedData,width,height);
         }

     }


     public static int findFrontCamera(){
            int cameraCount = 0;
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            cameraCount = Camera.getNumberOfCameras(); // get cameras number

            for ( int camIdx = 0; camIdx < cameraCount;camIdx++ ) {
                Camera.getCameraInfo( camIdx, cameraInfo ); // get camerainfo
                if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
                     // 代表摄像头的方位，目前有定义值两个分别为CAMERA_FACING_FRONT前置和CAMERA_FACING_BACK后置
                   return camIdx;
                 }
            }
            return -1;
     }

     public static int findBackCamera(){
         int cameraCount = 0;
         Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
         cameraCount = Camera.getNumberOfCameras(); // get cameras number

         for ( int camIdx = 0; camIdx < cameraCount;camIdx++ ) {
            Camera.getCameraInfo( camIdx, cameraInfo ); // get camerainfo
            if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK ) {
                 // 代表摄像头的方位，目前有定义值两个分别为CAMERA_FACING_FRONT前置和CAMERA_FACING_BACK后置
                 return camIdx;
            }
          }
         return -1;
     }

     public static Bitmap toImgScale(Bitmap bitmap, int nWidth, int nHeight) {
         //2、得到以上加载图片的高度跟宽度
         int height = bitmap.getHeight();
         int width = bitmap.getWidth();

         //3、定义要缩放成最终的图片高度跟宽度
       //  int nWidth = 640;
         //4、计算缩放比例
         float scaleWidth = ((float) nWidth)/width;
         float scaleHeight = ((float) nHeight)/height;


         //5、创建Matrix对象 Matrix是在Android中用于操作图像的类
         Matrix matrix = new Matrix();
         //6、使用Matrix对象跟缩放比例实现缩放图片
         matrix.postScale(scaleWidth, scaleHeight);

         //同样的，图片旋转只需要通过Matrix改变图片角度即可，生成图片跟7相同。

         //7、生成缩放后的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,width, height, matrix, true);

        return resizedBitmap;
     }

     public static String gerUserName(String userId){
         OUserInfo info = new OUserInfo();
         info.pbImageArray = new byte[640 * 480 * 2 * 5];
         info.pFacePos = new int[12 * 16];
         HWFaceLib.getInstance().GetUserInfobyID(Integer.parseInt(userId), info);

         return info.strName;
     }
 }
